<?php

/*
 *  老订单 使用当前文件跑一遍生成预估距离
 */

$serverFilePath =realpath(dirname(__FILE__)); ;//realpath(dirname(__FILE__)); //$_SERVER["SCRIPT_FILENAME"];
$doc_dir = strrpos($serverFilePath, ''.DIRECTORY_SEPARATOR.'crontab');
$doc_dir = substr($serverFilePath, 0, $doc_dir + 1);   //project root 
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'lib/Config.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'HybrisClass.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'Logging.php';
include_once $doc_dir . ''.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.'GaoDeAPIClass.php';
//$s = EXGold('上海上海市金山区万安街634号(近人民路)（营业时间8:00-21:00）');
//$o = EXGold('上海市浦东新区金桥路265号');
//$distance = getdistanceAction($s[0], $s[1], $o[0], $o[1]);
//echo '<pre>';
//var_dump($s);
//var_dump($o);
//var_dump($distance);die;

set_time_limit(0);
error_reporting(E_ALL);
header("Content-type:text/html;charset:utf-8");

$config_ini = $doc_dir . 'config/config.ini';

$ini_array = parse_ini_file($config_ini, true);
$db_array = $ini_array['DB'];
$getWebsite = $ini_array['WebSite'];
$con = mysqli_init();

mysqli_real_connect($con, $db_array['host'], $db_array['id'], $db_array['pwd'], $db_array['database'], $db_array['port']);
mysqli_set_charset($con, $db_array['encoding']);

$sql = " SELECT a.id,a.receiver_address,a.lat,a.lng,a.distance,b.front_province,b.front_city,b.front_area ,b.front_address FROM orders as a left join xd_store as b ON a.shop_no = b.store_id where a.source != '美团' and  a.source != '饿了么' and (a.distance is null  or a.lat is null  or a.lng is null or a.distance ='' or a.lat =''  or a.lng ='' ) ORDER BY a.id DESC LIMIT 0, 80 ";
$result = mysqli_query($con, $sql);
$res = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $res[] = $row;
}
if($res && count($res)){
    foreach ($res as $k => $val) {
        $address = $val['front_province'].$val['front_city'].$val['front_area'].$val['front_address'];  //门店地址
        $s = EXGold($address);  # 店铺原经纬度为百度 这里需要高德经纬度
        $o = EXGold($val['receiver_address']);   //收货地址
        $lng = round($o[0],5);
        $lat = round($o[1],5);
        if($s && count($s) > 0 && $o && count($o) > 0 ){
            $distance = getdistanceAction($s[0], $s[1], $lng, $lat);
            $distance = round($distance,2);
            $sql_edit = "update orders set distance = '$distance',lng = '$lng' ,lat = '$lat' where id =".$val['id'];
            $result = mysqli_query($con, $sql_edit);
        }else {
            $distance = '查无资料';
            $sql_edit = "update orders set distance = '$distance',lng = '－' ,lat = '－' where id =".$val['id'];
            $result = mysqli_query($con, $sql_edit);
        }
        echo '订单ID：'.$val['id'].'已更新'.'<br/>';
    }

}else{
    echo  '无需更新'.'<br/>';
}


# 兑换高德经纬度
function EXGold($address){
    $log = new Logging();
    $log->lfile('EXGold');
    $address = str_replace(' ','',$address);
    $log->lwrite(date('Y-m-d H:i:s').'  ad：'.$address.'');
    $GaoDeAPI = new GaoDeAPI();
    $r = $GaoDeAPI->getTrapezeAction($address);
    $location = [];
    if($r && count($r) > 0){
        $location = explode(',',$r['geocodes'][0]['location']);
    }
    $log->lwrite(date('Y-m-d H:i:s').'  res：'.json_encode($location,JSON_UNESCAPED_UNICODE).'');
    if($location && is_array($location) && count($location) > 1){
        return $location;
    }else{
        return '';
    }

}


/**
 * 求两个已知经纬度之间的距离,单位为米
 * @param lng1 $ ,lng2 经度
 * @param lat1 $ ,lat2 纬度
 * @return float 距离，单位米
 */
function getdistanceAction($lng1, $lat1, $lng2, $lat2) {
    $radLat1 = deg2rad($lat1);
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
    return $s;
}
